package com.cdc.dbdemo;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by cdc on 2018/4/4.
 */

public class  DBManager {
    private static MySqliteHelper helper;
    public static MySqliteHelper getHelper(Context context){
        if(helper==null){
              helper=new MySqliteHelper(context);
        }
        return helper;
    }

    public static void execSQL(SQLiteDatabase db,String sql){
        if(db!=null){
            if(sql!=null && !"".equals(sql)){
                db.execSQL(sql);
            }
        }
    }

    /**
     *
     * @param db
     * @param sql
     * @param selectionArgs  查询条件占位符
     * @return
     */
    public static Cursor selectBySql(SQLiteDatabase db, String sql,String [] selectionArgs){
        Cursor cursor=null;
        if(db!=null){
            if(sql!=null && !"".equals(sql)){
                cursor=db.rawQuery(sql,selectionArgs);
            }
        }
        return cursor;
    }

    public static List<Person> cursorToList(Cursor cursor){
        List<Person> lists=new ArrayList<>();
        while(cursor.moveToNext()){
            int id=cursor.getInt(cursor.getColumnIndex(DBConstants._id));
            String name=cursor.getString(cursor.getColumnIndex(DBConstants.NAME));
            int age=cursor.getInt(cursor.getColumnIndex(DBConstants.AGE));
            Person person=new Person(id,name,age);
            lists.add(person);
        }
        return lists;
    }
}
